package util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class EmailUtil {

    private static Properties config;

    static {
        try{
            config=new Properties();
            config.load(EmailUtil.class
                                 .getClassLoader()
                                 .getResourceAsStream("email.properties"));


        }catch (Exception e){
            e.printStackTrace();
            throw new ExceptionInInitializerError("EmailUtit初始化失败");
        }
    }




    public static void send(String toEmail,String title,String text){

        Session session=Session.getInstance(config, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getProperty("email.fromEmail"),
                                                  config.getProperty("email.password"));
            }
        });

//        session.setDebug(true);

        try{
            Message message=new MimeMessage(session);
            message.setFrom(new InternetAddress(config.getProperty("email.fromEmail")));
            message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toEmail));

            message.setSubject(title);

            message.setText(text);

            Transport.send(message);


        }catch (Exception e){
            e.printStackTrace();;
        }



    }


    public static void main(String[] args) {

        send("116958019@qq.com","测试","这是java发送的邮件");


    }














}
